import { useTranslation } from 'react-i18next';
import { useMessage } from '../components/messageApi';
import i18n from '../i18n/i18n';

// 创建一个单例用于存储message API引用
let messageApiRef: {
  error: (content: React.ReactNode, duration?: number, onClose?: () => void) => void;
} | null = null;

// 用于设置message API引用的函数
export const setMessageApiRef = (api: {
  error: (content: React.ReactNode, duration?: number, onClose?: () => void) => void;
}) => {
  messageApiRef = api;
};

// 网络错误类型
export enum NetworkErrorType {
  CONNECTION_ERROR = 'connection_error',  // 连接问题
  REQUEST_TIMEOUT = 'request_timeout',    // 请求超时
  NETWORK_UNAVAILABLE = 'network_unavailable', // 网络不可用
  UNKNOWN_ERROR = 'unknown_error'         // 未知错误
}

// 处理网络错误的函数
export const handleNetworkError = (error: any, type?: NetworkErrorType) => {
  // 确定错误类型
  let errorType = type || NetworkErrorType.UNKNOWN_ERROR;
  
  if (!type) {
    const errorMessage = error.message || '';
    const errorStack = error.stack || '';
    
    // 根据错误对象自动检测错误类型
    if (errorMessage.includes('timeout')) {
      errorType = NetworkErrorType.REQUEST_TIMEOUT;
    } else if (
      errorMessage.includes('Network Error') || 
      !navigator.onLine || 
      errorMessage.includes('network') || 
      errorMessage.includes('ERR_INTERNET_DISCONNECTED') ||
      errorStack.includes('ERR_INTERNET_DISCONNECTED') ||
      errorMessage.includes('Failed to fetch')
    ) {
      errorType = NetworkErrorType.NETWORK_UNAVAILABLE;
    } else if (
      errorMessage.includes('failed') || 
      errorMessage.includes('rejected') || 
      errorMessage.includes('abort')
    ) {
      errorType = NetworkErrorType.CONNECTION_ERROR;
    }
  }

  // 如果messageApiRef可用，直接使用它显示错误
  if (messageApiRef) {
    showErrorWithTranslation(errorType, messageApiRef);
  } else {
    // 记录到控制台，以防无法显示
    console.error('Network error occurred but messageApi is not available:', errorType, error);
  }
};

// 使用i18n翻译显示错误消息
export const showErrorWithTranslation = (errorType: NetworkErrorType, messageApi: any) => {
  // 获取翻译文本
  let errorMessage = '';
  
  // 构建翻译键
  const translationKey = `networkErrors.${errorType}`;
  
  try {
    // 使用导入的i18n实例
    if (i18n && i18n.isInitialized) {
      errorMessage = i18n.t(translationKey);
    } else {
      // 回退消息
      errorMessage = getFallbackErrorMessage(errorType);
      console.warn('i18n not initialized, using fallback error message');
    }
  } catch (err) {
    errorMessage = getFallbackErrorMessage(errorType);
    console.warn('Error using i18n translation:', err);
  }

  // 显示错误消息
  messageApi.error(errorMessage, 5000);  // 显示5秒
};

// 获取回退的错误消息（无法使用i18n时）
const getFallbackErrorMessage = (errorType: NetworkErrorType): string => {
  switch (errorType) {
    case NetworkErrorType.CONNECTION_ERROR:
      return 'Failed to connect to server. Please check your connection.';
    case NetworkErrorType.REQUEST_TIMEOUT:
      return 'Request timed out. Please try again later.';
    case NetworkErrorType.NETWORK_UNAVAILABLE:
      return 'Network is unavailable. Please check your internet connection.';
    case NetworkErrorType.UNKNOWN_ERROR:
    default:
      return 'An unknown network error occurred. Please try again later.';
  }
};

// React组件钩子，用于在组件中处理网络错误
export const useNetworkErrorHandler = () => {
  const { t } = useTranslation();
  const messageApi = useMessage();
  
  // 设置全局message API引用
  setMessageApiRef(messageApi);
  
  // 返回处理函数供组件使用
  return (error: any, type?: NetworkErrorType) => {
    // 确定错误类型
    let errorType = type || NetworkErrorType.UNKNOWN_ERROR;
    
    if (!type) {
      const errorMessage = error.message || '';
      const errorStack = error.stack || '';
      
      if (errorMessage.includes('timeout')) {
        errorType = NetworkErrorType.REQUEST_TIMEOUT;
      } else if (
        errorMessage.includes('Network Error') || 
        !navigator.onLine || 
        errorMessage.includes('network') || 
        errorMessage.includes('ERR_INTERNET_DISCONNECTED') ||
        errorStack.includes('ERR_INTERNET_DISCONNECTED') ||
        errorMessage.includes('Failed to fetch')
      ) {
        errorType = NetworkErrorType.NETWORK_UNAVAILABLE;
      } else if (
        errorMessage.includes('failed') || 
        errorMessage.includes('rejected') || 
        errorMessage.includes('abort')
      ) {
        errorType = NetworkErrorType.CONNECTION_ERROR;
      }
    }
    
    // 使用翻译显示错误
    try {
      const translationKey = `networkErrors.${errorType}`;
      const translatedMessage = t(translationKey);
      messageApi.error(translatedMessage, 5000);
    } catch (err) {
      // 如果翻译失败，使用回退消息
      console.warn('Translation failed, using fallback message:', err);
      messageApi.error(getFallbackErrorMessage(errorType), 5000);
    }
  };
};